package com.sam.im.heiqun.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.utils.ServiceDataAnalyse;

import org.greenrobot.eventbus.EventBus;

import java.net.URISyntaxException;

import io.socket.client.Ack;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

/**
 * Created by Joe on 2017/3/4.
 */

public class AcceptService extends Service {
    private static Socket socket;
    public AcceptService() {
        super();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("info","acceptservice===");
        App.initSocket(App.imIpAfterReady, App.tokenAfterReady);
        //initSocket(App.imIpAfterReady, App.tokenAfterReady);
    }
    public void initSocket(String address, String token) {
        try {
            IO.Options opts = new IO.Options();
            opts.forceNew = false;
            opts.reconnection = false;
            if (socket != null) {
                socket.close();
                socket = null;
            }
            socket = IO.socket("http://" + address + ":9092?token=" + token + "&device=1", opts);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                EventBus.getDefault().post(Constant.FRAGMENT_HIND_TITLE);//链接成功后发出通知
            }

        }).on("chat", new Emitter.Listener() {
            //聊天事件
            @Override
            public void call(final Object... args) {
                Ack ack = (Ack) args[args.length - 1];//最后一个参数为服务器的ack
                ack.call();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ServiceDataAnalyse.onMessage(args);
                    }
                }).start();
            }

        })
                .on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

                    @Override
                    public void call(Object... args) {
                        if (null != socket) {
                            socket.close();
                            socket = null;
                        }
                    }

                });
        socket.connect();
    }
}
